import React, { useRef, useState } from 'react';
import styled from 'styled-components';

const SwitchWrapper = styled.div`
  height: 45px;
  background: #ccc; 
  .switch-box {
    width: 60px;
    height: 35px;
    background: red;
    border-radius: 30px;
    span {
      display: inline-block;
      width: 35px;
      height: 35px;
      background: #eee;
      border-radius: 50%;
      transition: transform 200ms;
      transform: translate(0px, 0px);
    }
  }
`;

interface IProps {
  switchClick: (flag: boolean) => void
}

const SwitchCom: React.FC<IProps> = (props) => {
  const [flag, setFlag] = useState(true);

  const { switchClick } = props
  let spanDom: any = useRef()

  // useState 和不使用 去更新数据有什么区别？

  // setState() let flag = true
  // flag = flase

  // let flag = false;
  const transitionEvent = () => {
    if (flag) {
      spanDom.current.style.transform = `translate(25px, 0)`
      setFlag(false)
    } else {
      spanDom.current.style.transform = `translate(0px, 0)`
      setFlag(true)
    }
    // if (!flag) {
    //   // console.log(spanDom)
    //   spanDom.current.style.transform = `translate(25px, 0)`
    //   flag = true;
    // } else {
    //   spanDom.current.style.transform = `translate(0px, 0)`
    //   flag = false
    // }
    console.log("flag:", flag)
    // 回调函数在这儿传值影响了什么？
    switchClick(flag)
  }

  return <SwitchWrapper className="switch-wrapper">
    <div className="switch-box">
      <span ref={spanDom} onClick={() => transitionEvent()}></span>
    </div>
  </SwitchWrapper>
}

export default SwitchCom;